package com.acdc.utils;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * 微信JSSDK工具类
 */
public class JSSDKUtils {
    
    /**
     * 生成JSSDK签名
     * @param jsapiTicket JSAPI票据
     * @param nonceStr 随机字符串
     * @param timestamp 时间戳
     * @param url 当前页面URL
     * @return 签名
     */
    public static String generateJSSDKSignature(String jsapiTicket, String nonceStr, String timestamp, String url) {
        try {
            // 1. 对所有待签名参数按照字段名的ASCII码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串string1
            String string1 = "jsapi_ticket=" + jsapiTicket +
                           "&noncestr=" + nonceStr +
                           "&timestamp=" + timestamp +
                           "&url=" + url;
            
            // 2. 对string1进行sha1签名，得到signature
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(string1.getBytes("UTF-8"));
            
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("生成JSSDK签名失败", e);
        }
    }
    
    /**
     * 生成随机字符串
     * @return 随机字符串
     */
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    
    /**
     * 生成时间戳
     * @return 时间戳字符串
     */
    public static String generateTimestamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }
}
